package com.imddysc.springbootbatch001.config;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.job.flow.JobExecutionDecider;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableBatchProcessing
public class DeciderDemo {
	
	@Autowired
	private JobBuilderFactory jobBuilderFactory;
	
	@Autowired
	private StepBuilderFactory stepBuilderFactory;
	

	@Bean
	public Step deciderDemoJobstep3() {
		return stepBuilderFactory.get("deciderDemoJobstep3")
				.tasklet(new Tasklet() {

					@Override
					public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
						System.out.println("odd");
						return RepeatStatus.FINISHED;
					}
					
				}).build();
	}

	@Bean
	public Step deciderDemoJobstep2() {
		return stepBuilderFactory.get("deciderDemoJobstep2")
				.tasklet(new Tasklet() {

					@Override
					public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
						System.out.println("even");
						return RepeatStatus.FINISHED;
					}
					
				}).build();
	}

	@Bean
	public Step deciderDemoJobstep1() {
		return stepBuilderFactory.get("deciderDemoJobstep1")
				.tasklet(new Tasklet() {

					@Override
					public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
						System.out.println("deciderDemoJobstep1!!!");
						return RepeatStatus.FINISHED;
					}
					
				}).build();
	}
	
	
	//创建决策器
	@Bean
	public JobExecutionDecider myDecider() {
		return new MyDecider();
	}
	
	//创建JOB
	@Bean
	public Job deciderDemoJob() {
		return (Job) jobBuilderFactory.get("deciderDemoJob")
				.start(deciderDemoJobstep1())
				.next(myDecider())
				.from(myDecider()).on("even").to(deciderDemoJobstep2())
				.from(myDecider()).on("odd").to(deciderDemoJobstep3())
				.from(deciderDemoJobstep3()).on("*").to(myDecider())
				.end()
				.build();
				
	}
	
}
